package dao

import (
	"fmt"
	"gorm.io/gorm"
	"strings"
	"time"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/profit"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

// 查询KA用户列表
func (d *UserDao) GetBranchUserList(param *request.UserList) *dingo.ErrorWrap {

	var (
		lst    []*users.UserInfoWithKA
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Debug().
		Table("users u").
		Select("u.*", "r.name as role_name").
		Joins("left join roles r on r.id = u.role_id").
		Where("u.is_delete = 0").
		Where("u.is_admin = ?", param.IsAdmin)
		//Where("u.parent_id = ?", param.ParentId)
		//Where("u.is_place = ?", param.IsPlace)

	if param.SearchText != "" {
		db.Where("u.user_name like ?", fmt.Sprint("%", param.SearchText, "%"))
	}

	if param.Name != "" {
		db.Where("u.name like ?", fmt.Sprint("%", param.Name, "%"))
	}
	if param.Phone != "" {
		db.Where("u.phone = ?", param.Phone)
	}
	if param.Status > 0 {
		db.Where("u.status = ?", param.Status)
	}

	if param.UserNo != "" {
		db.Where("u.user_no = ?", param.UserNo)
	}

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("u.last_login_time >= ? and u.last_login_time <= ?", beginTime[0], beginTime[1])
	}

	// 排序
	//if param.SortField != "" && param.SortOrder == "ascend" {
	//	db.Order(fmt.Sprintf("u.%s asc", utils.String(param.SortField).SnakeCase()))
	//}
	//if param.SortField != "" && param.SortOrder == "descend" {
	//	db.Order(fmt.Sprintf("u.%s desc", utils.String(param.SortField).SnakeCase()))
	//}
	//if param.SortField == "" {
	//	db.Order("u.last_login_time desc, u.create_at desc")
	//}
	db.Order("u.create_at desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)

}

// 新增KA
func (d *UserDao) InsertBranchUser(param *request.AdminUserInsertReq) *dingo.ErrorWrap {

	db := global.Orm.Debug()
	err := db.Transaction(func(tx *gorm.DB) error {
		m := users.New().Mutate(
			users.WithCreateAt(dingo.Time(time.Now().Unix())),
			users.WithName(param.Name),
			users.WithUserName(param.UserName),
			users.WithNickName(param.UserName),
			users.WithPhone(param.Phone),
			users.WithPhoneCode("+86"),
			users.WithStatus(param.Status),
			users.WithPassword(utils.EncryptPassword(param.Password)),
			users.WithRoleId(param.RoleId),
			users.WithParentId(2),
			users.WithIsAdmin(param.IsAdmin),
			users.WithProfitType(param.ProfitType),
			users.WithProfitIsVisible(param.ProfitIsVisible),
			users.WithOrderIsVisible(param.OrderIsVisible),
			users.WithIncomeIsVisible(param.IncomeIsVisible),
			users.WithIsDraw(param.IsDraw),
			users.WithProfitProportion(param.ProfitProportion),
			users.WithSmProfitProportion(param.SmProfitProportion),
			users.WithIsPlace(3),
			users.WithIsCash(param.IsCash),
			users.WithUserNo(helper.PrefixBranchUserNo+time.Now().Format("20060102150405")),
		)
		if err := tx.Table("users").Create(&m).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		// 分成表 密码线 PCLc
		p := profit.New().Mutate(
			profit.WithCreateAt(dingo.Time(time.Now().Unix())),
			profit.WithUserID(m.ID),
			profit.WithSharedMode("pcl"),
			profit.WithDeviceTypeId(10),
			profit.WithProfitType(1),
			profit.WithProfitIsVisible(param.ProfitIsVisible),
			profit.WithProfitProportion(param.ProfitProportion),
		)

		if err := tx.Debug().Table("profits").Create(&p).Error; err != nil {
			return err
		}

		// 分成表 售货机 sm -- 后期用
		p2 := profit.New().Mutate(
			profit.WithCreateAt(dingo.Time(time.Now().Unix())),
			profit.WithUserID(m.ID),
			profit.WithSharedMode("cdb"),
			profit.WithDeviceTypeId(11),
			profit.WithProfitType(1),
			profit.WithProfitIsVisible(param.ProfitIsVisible),
			profit.WithProfitProportion(param.SmProfitProportion),
		)

		if err := tx.Debug().Table("profits").Create(&p2).Error; err != nil {
			return err
		}

		// 返回 nil 提交事务
		return nil
	})
	return dingo.ErrorIf(err, true)
}

// 更新分公司用户
func (d *UserDao) UpdateBranchUser(param *request.AdminUserInsertReq) *dingo.ErrorWrap {
	err := global.Orm.Transaction(func(tx *gorm.DB) error {
		m := users.New().Mutate(
			users.WithUpdateAt(dingo.Time(time.Now().Unix())),
			users.WithName(param.Name),
			users.WithUserName(param.UserName),
			users.WithNickName(param.UserName),
			users.WithPhone(param.Phone),
			users.WithStatus(param.Status),
			users.WithRoleId(param.RoleId),
			users.WithParentId(param.ParentId),
			users.WithIsAdmin(param.IsAdmin),
			//users.WithProfitType(param.ProfitType),
			//users.WithProfitIsVisible(param.ProfitIsVisible),
			users.WithIsDraw(param.IsDraw),
			users.WithProfitProportion(param.ProfitProportion),
			users.WithSmProfitProportion(param.SmProfitProportion),
		)
		tx.Debug().Table("users").Where("id = ?", param.Id).Model(&m).Updates(m)
		if err := tx.Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}

		// 分成表 通过user_id 修改两条数据
		p := profit.New().Mutate(
			profit.WithUpdateAt(dingo.Time(time.Now().Unix())),
			profit.WithProfitIsVisible(param.ProfitIsVisible),
			profit.WithProfitProportion(param.ProfitProportion),
		)

		tx.Debug().Table("profits").Where("user_id = ?", param.Id).Model(&p).Updates(p)
		if err := tx.Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		// 返回 nil 提交事务
		return nil
	})

	return dingo.ErrorIf(err, true)
}
